package top.kaoshanji.p2ch21a;

import top.kaoshanji.p2ch21a.support.GenericTest;

import java.lang.reflect.*;
import java.util.Arrays;
import java.util.List;

/**
 * 代码清单-p2ch21a-562页a：通过反射获取泛型信息的示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/28 17:52
 */
public class GenericDemo {

    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {

        Class<?> cls = GenericTest.class;

        // 类的类型参数
        for (TypeVariable t: cls.getTypeParameters()) {
            System.out.println(t.getName() + " extends " + Arrays.toString(t.getBounds()));
        }

        // 字段 - 泛型类型
        Field fu = cls.getDeclaredField("u");
        System.out.println(fu.getGenericType());

        // 字段 - 参数化的类型
        Field flist = cls.getDeclaredField("list");
        Type listType = flist.getGenericType();
        if (listType instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) listType;
            System.out.println("raw type: " + pType.getRawType() + ", type arguments:" + Arrays.toString(pType.getActualTypeArguments()));
        }

        // 方法的泛型类型
        Method m = cls.getMethod("test", new Class[]{List.class});
        for (Type t: m.getGenericParameterTypes()) {
            System.out.println(t);
        }

    }


}
